package acme.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class ClientManager {
	
	private static Map<API, List<ClientWorker>> workerMap = new HashMap<API, List<ClientWorker>>();
	private static final long MAX_INTERVAL = 60000;
	private static final long MIN_INTERVAL = 5000;
	private static final int MAX_THREADS = 10;
	private static Random random = new Random();
	private static Timer timer = null;
	
	static{
		TimerTask task = new MyTimerTask();
		timer = new Timer();
		timer.schedule(task, 60000 * 60, 60000 * 60);
	}
	
	public static void runWorkers(API api, int numWorkers){
		if(numWorkers > MAX_THREADS) numWorkers = MAX_THREADS;
		
		List<ClientWorker> workerList = workerMap.get(api);
		if(workerList == null){
			workerList = new ArrayList<ClientWorker>();
			workerMap.put(api, workerList);
		}
		
		int currentNum = workerList.size();
		
		if(currentNum > numWorkers){
			for(int i = 0; i < (currentNum - numWorkers); i++){
				ClientWorker w = workerList.get(0);
				w.stopWorking();
				workerList.remove(w);
			}
		}else if(numWorkers > currentNum){
			for(int i = 0; i < (numWorkers - currentNum); i++){
				long interval = Math.round(random.nextDouble() * MAX_INTERVAL);
				if(interval < MIN_INTERVAL) interval = MIN_INTERVAL;
				ClientWorker w = new ClientWorker(api, Keys.getRandomKey(api), interval);
				workerList.add(w);
				
				Thread t = new Thread(w);
				t.start();
			}
		}
		
	}
	
	public static Map<API, List<ClientWorker>> getWorkerMap(){
		return workerMap;
	}
	
	private static class MyTimerTask extends TimerTask{

		@Override
		public void run() {
			Map<API, List<ClientWorker>> apiMap = getWorkerMap();
			for(API api : apiMap.keySet()){
				int num = apiMap.get(api).size();
				runWorkers(api, 0);
				runWorkers(api, num);
			}
		}
	}

}
